<template>
  <div>
    <div class="distribution">
      <div class="lme">
        <el-input class="elIp" clearable v-model="filterMenu" placeholder="请输入内容"></el-input>
        <el-menu default-active="2" class="el-menu-vertical-demo">
          <el-menu-item v-for="(i,ii) in menuList" :key="ii" :index="i.distributorCode"
            @click="getPageData(i)">
            <span slot="title">{{i.distributorName}}</span>
          </el-menu-item>
        </el-menu>
      </div>
      <!-- <el-button size="mini" @click="goback">返回</el-button> -->
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="160px">
        <el-form-item label="层级：" prop="level">
          <el-radio v-model="ruleForm.level" v-for="(i,ii) in levelList" :key="ii" :label="i.key">
            {{i.value}}</el-radio>
        </el-form-item>
        <el-form-item label="等级：" prop="sharelevelid">
          <el-select v-model="ruleForm.sharelevelid" placeholder="请选择分销等级">
            <el-option v-for="v in sharelevelList" :key="v.id" :label="v.share_level_name"
              :value="v.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分销内购：" prop="inpurchase">
          <el-radio v-model="ruleForm.inpurchase" v-for="(i,ii) in inpurchaseList" :key="ii"
            :label="i.key">{{i.value}}</el-radio>
          <div>内购优惠开启后，分销员自己购买时，下单可以给自己返佣</div>
        </el-form-item>
        <el-form-item label="锁定下线条件：" prop="locksubordinate">
          <el-radio v-model="ruleForm.locksubordinate" v-for="(i,ii) in locksubordinateList"
            :key="ii" :label="i.key">{{i.value}}</el-radio>
        </el-form-item>
        <el-form-item label="是否审核：" prop="audit">
          <el-radio v-model="ruleForm.audit" v-for="(i,ii) in inpurchaseList" :key="ii"
            :label="i.key">
            {{i.value}}</el-radio>
        </el-form-item>
        <!-- <el-form-item label="越级升级：">
        <el-radio v-model="ruleForm.upgrade" v-for="(i,ii) in upgradeList" :key="ii" :label="i.key">
          {{i.value}}</el-radio>
      </el-form-item>
      <el-form-item label="升级审核：">
        <el-radio v-model="ruleForm.upgradeaudit" v-for="(i,ii) in auditList" :key="ii" :label="i.key">{{i.value}}</el-radio>
      </el-form-item> -->
        <el-form-item label="成为分销员条件：">
          <el-radio v-model="ruleForm.becomingdistributor" v-for="(i,ii) in becomingdistributorList"
            :key="ii" :label="i.key">{{i.value}}</el-radio>
          <div v-if="ruleForm.becomingdistributor == 1">
            <el-button @click="SelectProduct" type="primary" size="mini">选择商品</el-button>
            <el-table ref="tableData" :data="tableData" style="width: 100%" max-height="300"
              size="mini">
              <el-table-column label="商品图片">
                <template slot-scope="scope">
                  <img class="images" :src="scope.row.pic_path" />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="商品名称" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="text" @click="del(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label="消费累计金额：" v-if="ruleForm.becomingdistributor == 2">
          <el-input-number v-model="ruleForm.consumptionamount" min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="完善资料：">
          <el-radio v-model="ruleForm.improvedata" v-for="(i,ii) in auditList" :key="ii"
            :label="i.key">{{i.value}}</el-radio>
          <div>成为分销员条件如果选择自助申请，完善资料必须选择需要</div>
        </el-form-item>
        <el-form-item label="表单关联：" v-show="ruleForm.improvedata == 1" prop="formcontent">
          <el-select v-model="ruleForm.formcontent" placeholder="请选择表单关联">
            <el-option v-for="(i,ii) in formcontentList" :key="ii" :label="i.label"
              :value="i.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="提现方式：">
          <div class="flex">
            <el-checkbox v-model="ruleForm.payAlipay" :true-label="1"
              :false-label="0">支付宝</el-checkbox>
            <div v-show="payAliShow">
              <el-button type="text" class="mr20">支付账户</el-button>
              <el-select size="small" class="w200" clearable filterable
                v-model="ruleForm.alipayCode">
                <el-option v-for="v in PaysList" :key="v.id" :label="v.value" :value="v.key">
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="flex">
            <el-checkbox v-model="ruleForm.payWeChat" :true-label="1"
              :false-label="0">微信</el-checkbox>
            <div v-show="weChatShow">
              <el-button type="text" class="mr20">支付账户</el-button>
              <el-select size="small" class="w200" clearable filterable
                v-model="ruleForm.weChatCode">
                <el-option v-for="v in PaysList" :key="v.id" :label="v.value" :value="v.key">
                </el-option>
              </el-select>
            </div>
          </div>
        </el-form-item>
        <!-- <el-form-item label="分销商背景图：">
        <VolUploadUpgrade :fileInfo="ruleForm.backgroundpic"></VolUploadUpgrade>
      </el-form-item> -->
        <!-- <el-form-item label="申请协议：">
        <el-radio v-model="ruleForm.agreement" v-for="(i,ii) in agreementList" :key="ii" :label="i.key">
          {{i.value}}</el-radio>
      </el-form-item> -->
        <!-- <el-form-item label="商品结算方式：">
        <el-radio v-model="ruleForm.settlementmethod" v-for="(i,ii) in settlementmethodList" :key="ii" :label="i.key">{{i.value}}</el-radio>
        <div>商品价: 商品实际售价/规格价，实际支付价: 实际支付的费用(不含运费)</div>
      </el-form-item>
      <el-form-item label="佣金结算方式：">
        <el-radio v-model="ruleForm.commissionpay" v-for="(i,ii) in commissionpayList" :key="ii" :label="i.key">{{i.value}}</el-radio>
      </el-form-item>
      <el-form-item label="退款扣除佣金：">
        <el-radio v-model="ruleForm.commissionrefund" v-for="(i,ii) in commissionrefundList" :key="ii" :label="i.key">{{i.value}}</el-radio>
      </el-form-item>
      <el-form-item label="退款扣除分销业绩：">
        <el-radio v-model="ruleForm.achievementrefund" v-for="(i,ii) in commissionrefundList" :key="ii" :label="i.key">{{i.value}}</el-radio>
      </el-form-item> -->
        <el-form-item>
          <el-button type="primary" :disabled="distributorCode == ''"
            @click="submitForm('ruleForm')" v-loading="loading">保存</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog title="选择商品" :visible.sync="dialogVisible" width="70%">
      <div class="flex heisc">
        <el-tree class="heisc w300" ref="tree" :data="CodityClaifa" show-checkbox node-key="id"
          :props="{ multiple: true }" @check="changeCascder">
        </el-tree>
        <el-table ref="multipleTable" :data="tableData2" @selection-change="handleSelectionChange"
          size="mini" height="350">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column label="商品图片">
            <template slot-scope="scope">
              <img class="images" :src="scope.row.pic_path" />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="商品名称" />
        </el-table>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="commodity('ruleForm')">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import VolBox from "@/components/basic/VolBox.vue";
export default {
  name: "distribution",
  components: {
    VolBox,
    VolUploadUpgrade: () => import("@/components/basic/VolUploadUpgrade.vue"),
  },
  data() {
    return {
      ruleForm: {
        level: 0,
        upgradeaudit: 0,
        upgrade: 0,
        locksubordinate: 0,
        audit: 0,
        inpurchase: 0,
        improvedata: 0,
        becomingdistributor: 0,
        backgroundpic: [],
        commissionpay: 0,
        commissionrefund: 0,
        achievementrefund: 0,
        settlementmethod: 0,
        agreement: 0,
        consumptionamount: 0,
        formcontent: "",
        goodids: [],
        sharelevelid: "",
        payAlipay: 0,
        payWeChat: 0,
        alipayCode: "",
        weChatCode: "",
      },
      levelList: [
        {
          value: "关闭",
          key: 0,
        },
        {
          value: "一级",
          key: 1,
        },
        {
          value: "二级",
          key: 2,
        },
        {
          value: "三级",
          key: 3,
        },
      ],
      inpurchaseList: [
        {
          value: "关闭",
          key: 0,
        },
        {
          value: "开启",
          key: 1,
        },
      ],
      locksubordinateList: [
        {
          value: "点击分享链接",
          key: 0,
        },
        {
          value: "首次支付",
          key: 1,
        },
        {
          value: "成为分销员",
          key: 2,
        },
      ],
      auditList: [
        {
          value: "不需要",
          key: 0,
        },
        {
          value: "需要",
          key: 1,
        },
      ],
      upgradeList: [
        {
          value: "不允许",
          key: 0,
        },
        {
          value: "允许",
          key: 1,
        },
      ],
      becomingdistributorList: [
        {
          value: "自助申请",
          key: 0,
        },
        {
          value: "购买任意商品",
          key: 1,
        },
        {
          value: "消费累计",
          key: 2,
        },
      ],
      agreementList: [
        {
          value: "不显示",
          key: 0,
        },
        {
          value: "显示",
          key: 1,
        },
      ],
      settlementmethodList: [
        {
          value: "商品价",
          key: 0,
        },
        {
          value: "实际支付价",
          key: 1,
        },
      ],
      commissionpayList: [
        {
          value: "支付后结算",
          key: 0,
        },
        {
          value: "确认收货后结算",
          key: 1,
        },
        {
          value: "订单完成结算",
          key: 2,
        },
        {
          value: "手动打款",
          key: 3,
        },
      ],
      commissionrefundList: [
        {
          value: "不折扣",
          key: 0,
        },
        {
          value: "折扣",
          key: 1,
        },
      ],
      formcontentList: [],
      imageUrl: "",
      xzspStatus: false,
      dialogVisible: false,
      tableData: [],
      tableData2: [],
      CodityClaifa: [],
      multipleSelection: [],
      SRCL: "",
      STATUS: false,
      loading: false,
      distributorCode: "",
      rules: {
        level: [{ required: true, message: "请选择层级", trigger: "change" }],
        sharelevelid: [
          { required: true, message: "请选择等级", trigger: "change" },
        ],
        inpurchase: [
          { required: true, message: "请选择分销内购", trigger: "change" },
        ],
        locksubordinate: [
          { required: true, message: "请选择锁定下线条件", trigger: "change" },
        ],
        audit: [
          { required: true, message: "请选择是否审核", trigger: "change" },
        ],
      },
      sharelevelList: [],
      payAliShow: false,
      weChatShow: false,
      PaysList: [],
      menuList: [],
      filterMenu: "",
    };
  },
  watch: {
    "ruleForm.improvedata"(n, o) {
      if (n == 1) {
        let obj = {
          formcontent: [
            { required: true, message: "请选择表单关联", trigger: "change" },
          ],
        };
        this.rules = Object.assign({}, this.rules, obj);
      } else {
        if (this.rules.hasOwnProperty("formcontent")) {
          delete this.rules.formcontent;
        }
      }
    },
    "ruleForm.payAlipay"(n, o) {
      if (n == 1) {
        this.payAliShow = true;
      } else {
        this.payAliShow = false;
        this.ruleForm.alipayCode = "";
      }
    },
    "ruleForm.payWeChat"(n, o) {
      if (n == 1) {
        this.weChatShow = true;
      } else {
        this.weChatShow = false;
        this.ruleForm.payWeChat = "";
      }
    },
    filterMenu(newval, oldval) {
      if (newval != "") {
        this.menuList = this.menuList2.filter((i, ii, iii) => {
          return i.distributorName.includes(newval);
        });
      } else {
        this.menuList = this.menuList2;
      }
    },
  },
  created() {
    this.SRCL = this.http.ipAddress;
    this.GetProductType();
    this.getSharelevelData(); //等级数据
    this.getMenu();
  },
  methods: {
    getMenu() {
      let params = {
        page: 1,
        rows: 30,
        sort: "createDate",
        order: "desc",
        wheres:
          '[{"name":"distributorType","value":"2006,2004","displayType":"checkbox"}]',
      };
      this.http
        .post("api/DistributorNews/getPageData", params, false)
        .then((reslut) => {
          this.menuList = reslut.rows;
          this.menuList2 = reslut.rows;
        });
    },
    getSharelevelData() {
      let params = {
        page: 0,
        rows: 0,
        sort: "createDate",
        order: "desc",
        wheres: "[]",
      };
      this.http
        .post("api/ShareLevel/getPageData", params, false)
        .then((reslut) => {
          if (reslut.status == 0 && reslut.rows) {
            this.sharelevelList = reslut.rows;
            if (!this.ruleForm.sharelevelid) {
              this.ruleForm.sharelevelid = reslut.rows.length
                ? reslut.rows[0].id
                : "";
            }
          }
        });
      this.http
        .post("/api/Dictionary/GetVueDictionary", ["Pays"])
        .then((res) => {
          res.forEach((i) => {
            if (i.dicNo == "Pays") {
              this.PaysList = i.data;
            }
          });
        });
    },
    getPageData(c) {
      this.distributorCode = c.distributorCode;
      let params = {
        order: "desc",
        page: 1,
        rows: 30,
        sort: "createDate",
        wheres: "[]",
      };
      this.http.post("api/Form/GetFromData", params).then((res) => {
        this.formcontentList = res.rows.map((i) => {
          return {
            value: i.id.toString(),
            label: i.form_name,
          };
        });
      });
      let params2 = {
        order: "desc",
        page: 1,
        rows: 30,
        sort: "createDate",
        wheres: `[{\"name\":\"distributorCode\",\"value\":\"${this.distributorCode}\",\"displayType\":\"text\"}]`,
      };
      this.http
        .post(
          "api/Small_user_distributors_system/GetPageDataDisSystem",
          params2
        )
        .then((res) => {
          if (res.rows.length > 0) {
            res.rows[0].backgroundpic == null
              ? (res.rows[0].backgroundpic = [])
              : "";
            if (typeof res.rows[0].backgroundpic == "string") {
              res.rows[0].backgroundpic = res.rows[0].backgroundpic.split(",");
            }
            this.ruleForm = res.rows[0];
            this.tableData = JSON.parse(this.ruleForm.goodids);
            this.STATUS = true;
            if (res.rows[0].payWeChat == 1) {
              this.weChatShow = true;
            } else {
              this.weChatShow = false;
              this.ruleForm.payWeChat = "";
            }
            if (res.rows[0].payAlipay == 1) {
              this.payAliShow = true;
            } else {
              this.payAliShow = false;
              this.ruleForm.alipayCode = "";
            }
          } else {
            this.STATUS = false;
          }
        });
    },
    async photoOnChange(file) {
      let formData = new FormData();
      formData.append("fileInput", file.raw);
      let data = await this.http.post(
        "api/Small_user_distributors_system/Upload",
        formData
      );
      this.ruleForm.backgroundpic.push(data.data + file.raw.name);
    },
    GetProductType() {
      this.http.get("api/producttypes/GetProductType").then((res) => {
        function arrReduce(someArr) {
          for (let i = 0; i < someArr.length; i++) {
            if (someArr[i].children) {
              arrReduce(someArr[i].children);
              someArr[i].label = someArr[i].typeName;
              someArr[i].value = someArr[i].id;
            } else {
              someArr[i].label = someArr[i].typeName;
              someArr[i].value = someArr[i].id;
            }
          }
        }
        arrReduce(res.data);
        this.CodityClaifa = res.data;
      });
    },
    SelectProduct() {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection();
        this.tableData.forEach((item) => {
          this.$refs.multipleTable.toggleRowSelection(item);
        });
      });
    },
    changeCascder() {
      let v = this.$refs.tree.getCheckedNodes();
      let params = {
        typeid: v.length > 0 ? v.map((i) => i.value).join(",") : "",
      };
      this.http
        .post("api/Mall_good/GetMallDistributionGoods", params)
        .then((res) => {
          this.tableData2 = res.data;
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    commodity() {
      this.dialogVisible = false;
      this.tableData = this.multipleSelection;
    },
    del(i, v) {
      this.tableData.splice(i, 1);
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ruleForm.formcontent =
            this.ruleForm.improvedata == 0 ? "" : this.ruleForm.formcontent;
          this.ruleForm.distributorCode = this.distributorCode;
          if (this.ruleForm.becomingdistributor == 1) {
            this.ruleForm.goodids = this.tableData.map((i) => {
              return {
                goods_id: i.goods_id,
                name: i.name,
                pic_path: i.pic_path,
              };
            });
          } else {
            this.ruleForm.goodids = [];
          }
          let params = {
            delKeys: null,
            detailData: [],
            mainData: JSON.parse(JSON.stringify(this.ruleForm)),
          };
          if (params.mainData.backgroundpic.length) {
            params.mainData.backgroundpic =
              params.mainData.backgroundpic.join();
          } else {
            params.mainData.backgroundpic = "";
          }
          if (!this.STATUS) {
            this.loading = true;
            this.http
              .post("api/Small_user_distributors_system/AddDisSystem", params)
              .then((res) => {
                if (res.status) {
                  this.$Message.success("保存成功!");
                  this.loading = false;
                }
              });
          } else {
            params.detailData = null;
            this.loading = true;
            this.http
              .post(
                "api/Small_user_distributors_system/UpdateDisSystem",
                params
              )
              .then((res) => {
                if (res.status) {
                  this.$Message.success("保存成功!");
                  this.loading = false;
                }
              });
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avataruploadertext {
  text-align: left;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.distribution {
  padding: 20px;
  display: flex;
  height: 100%;
  width: 100%;
  position: absolute;
  .lme {
    width: 250px;
    height: 100%;
  }
  .el-menu {
    height: calc(100% - 40px);
    overflow-y: auto;

    .el-menu-item {
      height: 31px;
      line-height: 32px;
    }
  }
  .el-form {
    overflow-y: auto;
    width: 100%;
  }

  .w200 {
    width: 200px;
  }
  .mr20 {
    margin-left: 20px;
  }
}
.boxButtond {
  width: 100%;
  margin-bottom: 10px;
  max-height: 100px;
  overflow-y: auto;
}
.images {
  height: 50px;
  width: 50px;
}
.flex {
  display: flex;
}
.heisc{
  height: 350px;
  overflow-y: auto;
}
.w300{
  width: 300px;
}
</style>
